<?php

/**
 * Folder class
 *
 * @author Julot <andy.julot@gmail.com>
 * @since Tuesday, June 21, 2011. 09:57 AM
 */
class Folder extends Path {

	private $_folders = array();
	private $_files = array();
	private $_imageFiles = array();

	public function getFolders() {
		if ($this->_folders) return $this->_folders;

		$dir = opendir($this->_path);
		if (!$dir) return $this->_folders;

		while ($object = readdir($dir)) {
			$path = $this->_path . DIRECTORY_SEPARATOR . $object;
			if (is_dir($path) && ($object != ".") && ($object != "..")) {
				$this->_folders[] = new self($path);
			}
		}
		closedir($dir);
		asort($this->_folders);
		return $this->_folders;
	}

	public function getFiles() {
		if (!$this->_files) {
			if (is_dir($this->_path)) {
				$dir = opendir($this->_path);
				while (false !== $object = readdir($dir)) {
					$path = $this->_path . DIRECTORY_SEPARATOR . $object;
					if (is_file($path)) {
						if (strpos($path, '.thumb.') === false) {
							$this->_files[] = new File($path);
						}
					}
				}
			}
			sort($this->_files);
		}
		return $this->_files;
	}

	public function getImageFiles() {
		if (!$this->_imageFiles) {
			if (is_dir($this->_path)) {
				$dir = opendir($this->_path);
				while (false !== $object = readdir($dir)) {
					$path = $this->_path . DIRECTORY_SEPARATOR . $object;
					if (is_file($path)) {
						if (strpos($path, '.thumb.') === false) {
							$image = new ImageFile($path);
							if ($image->isImage()) {
								$this->_imageFiles[] = $image;
							}
						}
					}
				}
			}
			sort($this->_imageFiles);
		}
		return $this->_imageFiles;
	}

	protected function _generateListData($folder, $parent, $level=1) {
		$listData = array();
		$subLevel = $level + 1;
		foreach ($folder->folders as $sub) {
			$prefix = '&nbsp;|' . str_repeat('--', $level);
			$value = $sub->basename;
			if ($parent) $key = "$parent/$value";
			else $key = $value;
			$listData[$key] = "$prefix$value";
			if (count($sub->folders)) {
				$subListData = $this->_generateListData($sub, $key, $subLevel);
				foreach ($subListData as $key=>$value) {
					$listData[$key] = $value;
				}
			}
		}
		return $listData;
	}

	/**
	 * Generates the data suitable for list-based HTML elements.
	 *
	 * @return array the list data that can be used in dropDownList, listBox,
	 *     etc.
	 */
	public function listData() {
		return $listData = $this->_generateListData($this, false);
	}

	public function delete() {
		try {
			rmdir($this->path);
			return true;
		} catch (Exception $exc) {
			return false;
		}
	}

	public function addFolder($name) {
		$path = "$this->_path/$name";
		if (!file_exists($path)) return mkdir($path);
		return false;
	}

}
